package com.lisa.auto.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.C3CarInfo;
import com.lisa.auto.entity.Vehicle;
import com.lisa.auto.entity.VehicleArea;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.C3CarInfoMapper;
import com.lisa.auto.service.C3CarInfoService;
import com.lisa.auto.service.VehicleAreaService;
import com.lisa.auto.util.basic.BaseException;
import com.lisa.auto.util.basic.BaseResponse;
import demo.C3ApiDemo;
import demo.request.CarInfoRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 车况信息 服务实现类
 * </p>
 *
 * @author suohao
 * @since 2019-12-20
 */
@Service
public class C3CarInfoServiceImpl extends ServiceImpl<C3CarInfoMapper, C3CarInfo> implements C3CarInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(C3CarInfoServiceImpl.class);

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Autowired
    private VehicleAreaService vehicleAreaService;

    //@Override
//    public C3CarInfo getCarInfo(String vin) {
//
//        if ("".equals(vin) || vin==null){
//            throw new BaseException("车架号不能为空");
//        }
//        EntityWrapper<C3CarInfo> ew = new EntityWrapper<>();
//        ew.eq("vin",vin);
//        ew.orderBy("gmt_create",false);
//        List<C3CarInfo> c3CarInfoList = baseMapper.selectList(ew);
//        if (c3CarInfoList!=null && c3CarInfoList.size()!=0){
//            return c3CarInfoList.get(0);
//        }
//
//        return null;
//    }
    @Override
    public void getCarInfoToC3(String vin){
        try {
            String url= c3url+ C3UrlEnum.CARINFOURL.getUrl();
            CarInfoRequest request = new CarInfoRequest();
            request.setVin(vin);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.get(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)){
                BaseResponse<C3CarInfo> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()){
                    throw new BaseException("获取实时车况信息:"+baseResponse.getReturnErrMsg());
                }
                if (baseResponse.getData()!=null){
                    baseMapper.insert(baseResponse.getData());
                }
            }
        }catch (Exception e){
            LOGGER.error("C3CarInfoServiceImpl.getCarInfoToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public Page<Map<String, Object>> getVehicleList(Page<Map<String, Object>> page) {
        Page<Map<String, Object>> pageVo = new Page<>();
        Map<String, Object> condition = page.getCondition();
        EntityWrapper<Vehicle> ew = getEntityWrapper(condition);
        List<Map<String, Object>> maps=baseMapper.getVehicleList(ew);
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(maps);
        return pageVo;
    }

    @Override
    public List<Map<String, Object>> getTotalDistance(String vin, String startTime, String endTime) {
        if (StringUtils.isBlank(vin)){
            throw new BaseException("车架号不能为空");
        }
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)){
            throw new BaseException("请选择时间区间");
        }
        List<Map<String ,Object>> maps = baseMapper.getTotalDistance(vin,startTime,endTime);
        return maps;
    }

    @Override
    public List<Map<String, Object>> getVehicleSpeed(String vin, String startTime, String endTime) {
        if (StringUtils.isBlank(vin)){
            throw new BaseException("车架号不能为空");
        }
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)){
            throw new BaseException("请选择时间区间");
        }
        List<Map<String ,Object>> maps = baseMapper.getVehicleSpeed(vin,startTime,endTime);
        return maps;
    }

    private EntityWrapper<Vehicle> getEntityWrapper(Map<String, Object> condition) {
        EntityWrapper<Vehicle> ew = new EntityWrapper();
        if (condition.get("vin")!=null && !"".equals(condition.get("vin"))){
            ew.eq("a.vin",condition.get("vin"));
        }
        if (condition.get("plateLicenseNo")!=null && !"".equals(condition.get("plateLicenseNo"))){
            ew.eq("a.plate_license_no",condition.get("plateLicenseNo"));
        }
        if (condition.get("company")!=null && !"".equals(condition.get("company"))){
            ew.eq("a.company",condition.get("company"));
        }
        if (condition.get("driverName")!=null && !"".equals(condition.get("driverName"))){
            ew.eq("driver_name",condition.get("driverName"));
        }
        List<VehicleArea> list = vehicleAreaService.getVehicleAreaList(condition);
        List<Long> areaIds = new ArrayList<>();
        if (list!=null && !list.isEmpty()){
            for (VehicleArea area : list) {
                areaIds.add(area.getId());
            }
            ew.in("area_id",areaIds);
        }
        return ew;
    }


}
